import pygame
import random

# 初始化 pygame
pygame.init()

# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

# 设置窗口尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置窗口标题
pygame.display.set_caption("打砖块游戏")

# 定义挡板
paddle_width = 100
paddle_height = 15
paddle = pygame.Rect(screen_width // 2 - paddle_width // 2, screen_height - 50, paddle_width, paddle_height)

# 定义小球
ball_diameter = 10
ball = pygame.Rect(screen_width // 2 - ball_diameter // 2, screen_height // 2 - ball_diameter // 2, ball_diameter, ball_diameter)
ball_speed_x = 5 * random.choice((1, -1))
ball_speed_y = 5 * random.choice((1, -1))

# 定义砖块
brick_rows = 5
brick_cols = 7
brick_width = 75
brick_height = 20
brick_padding = 10
brick_offset_top = 30
bricks = [pygame.Rect(col * (brick_width + brick_padding) + brick_padding,
                      row * (brick_height + brick_padding) + brick_offset_top,
                      brick_width, brick_height)
          for row in range(brick_rows) for col in range(brick_cols)]

# 初始化得分
score = 0

# 定义字体
font = pygame.font.SysFont(None, 35)

# 游戏循环标志
running = True

# 游戏主循环
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 移动挡板
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle.left > 0:
        paddle.move_ip(-10, 0)
    if keys[pygame.K_RIGHT] and paddle.right < screen_width:
        paddle.move_ip(10, 0)

    # 移动小球
    ball.move_ip(ball_speed_x, ball_speed_y)

    # 碰撞检测 - 窗口边缘
    if ball.left <= 0 or ball.right >= screen_width:
        ball_speed_x = -ball_speed_x
    if ball.top <= 0:
        ball_speed_y = -ball_speed_y
    if ball.bottom >= screen_height:
        running = False  # 游戏结束

    # 碰撞检测 - 挡板
    if ball.colliderect(paddle):
        ball_speed_y = -ball_speed_y

    # 碰撞检测 - 砖块
    brick_collision_index = ball.collidelist(bricks)
    if brick_collision_index >= 0:
        hit_brick = bricks.pop(brick_collision_index)
        ball_speed_y = -ball_speed_y
        score += 999999  # 增加得分

    # 绘制所有元素
    screen.fill(black)
    pygame.draw.rect(screen, white, paddle)
    pygame.draw.ellipse(screen, white, ball)
    for brick in bricks:
        pygame.draw.rect(screen, green, brick)

    # 绘制得分
    score_text = font.render(f"Score: {score}", True, white)
    screen.blit(score_text, (10, 10))

    # 更新屏幕显示
    pygame.display.flip()

    # 控制游戏帧率
    pygame.time.Clock().tick(60)

# 游戏结束
screen.fill(black)
game_over_text = font.render(f"Game Over, Your Score: {score}", True, white)
screen.blit(game_over_text, (screen_width // 2 - 150, screen_height // 2 - 20))
pygame.display.flip()
pygame.time.wait(3000)  # 等待3秒

pygame.quit()